import axios from "axios"
import router from '../router/router'

// 创建 axios 实例
export const Axios = axios.create({
  timeout: 15000
});

window.cancelInterface=[]
//POST传参序列化(添加请求拦截器)
// 在发送请求之前做某件事
axios.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(cancel=>{
      if(!window.cancelInterface){window.cancelInterface=[]}
      window.cancelInterface.push({cancel})
    })
    if (localStorage.token) {
      config.headers.Authorization = 'Bearer ' + localStorage.token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//返回状态判断(添加响应拦截器)
axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8';
axios.interceptors.response.use(
  res => {
    if (res.data.code == "401") {
      router.push({
        path: "/login",
        query: { redirect: location.hostname }
      });
      return;
    }
    return res;
  },
  error => {
    if (error.response.status === 401 || error.response.status === 403) {
      router.push({
        path: "/login",
        query: { redirect: location.hostname }
      });
    } else if (error.response.status === 500) {
      // 服务器错误
      return Promise.reject(error.response.data);
    }
    // 返回 response 里的错误信息
    return Promise.reject(error.response.data);
  }
);

// 将 Axios 实例添加到Vue的原型对象上
export default {
  install(Vue) {
    Object.defineProperty(Vue.prototype, "$http", { value: Axios });
  }
};
